<script setup lang="ts">
import {nextTick, onMounted, reactive, ref} from "vue";
import {expertAddApi, expertEditApi, getTeacherList} from "@/services/expertGroup.ts";
import {tableBorder} from "@/utils/border/table-border.ts";
import {getDictByParentCode, listNormalRacetrack, listRacetrack} from "@/services/commonApi.ts";
import {TableRowSelectionProps} from "@arco-design/web-react";
import useFormSubmit from "@/hooks/useFormSubmit.ts";
import {FormInstance, Message} from "@arco-design/web-vue";
import ExpertDetailModal from "@/pages/review/expertGroup/expertDetailModal.vue";

const emits = defineEmits<{
  (e: 'list'): void
}>()

const props = defineProps<{
  moduleId: string
}>()

const detailRef = ref<{
  init: (data: any) => void
}>()

const rowSelection = reactive<TableRowSelectionProps>({
  type: "checkbox",
  selectedRowKeys: [],
})

const formRef = ref<FormInstance>();

const handleSubmit = useFormSubmit(formRef);

const modalRef = ref()

const option = reactive({
  visible: false,
  title: '',
  okLoading: false,
  groupId: '',
  city: '',
  channel: '',
  "参赛项目来源": [],
  "赛道": [],
  type: ""
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
});

const data = ref<any[]>([])

const formData = reactive<{
  groupName: string
  teacherIds: string[]
}>({
  groupName: "",
  teacherIds: []

})


function getList () {
  // data.value = []
  getTeacherList({
    current: pagination.current,
    size: pagination.pageSize,
    groupId: option.groupId,
    city: option.city,
    channel: option.channel
  }).then(res => {
    if (res.code === 200) {
      data.value = res.data.records
      pagination.total = res.data.total
    }
  })
}

const handleSearch = () => {
  handlePageChange(1)
}

const handleReset = () => {
  option.city = ""
  option.channel = ""
  nextTick(() => {
    handleSearch()
  })
}

const handlePageChange = (page: number) => {
  pagination.current = page
  getList()
}

const handleSelect = (rowKeys: string[]) => {
  formData.teacherIds = rowKeys
}

const handleDetail = (row: any) => {
  detailRef.value?.init(row)
}

const handleOk = () => {
  if (option.type === "1") {
    expertAddApi({
      groupName: formData.groupName,
      teacherIds: formData.teacherIds.filter(item => item).join(','),
      moduleId: props.moduleId
    }).then(res => {
      if (res.code === 200) {
        Message.success("添加专家组成功");
        handleCancel();
        emits("list");
      }
    })
  } else {
    console.log(formData.teacherIds.join(','))
    // 1950847128885129218
    console.log(formData.groupName)

    expertEditApi({
      groupName: formData.groupName,
      teacherIds: formData.teacherIds.filter(item => item).join(','),
      // teacherIds: '1950847129065484289,1950847129140981761,1950847128885129218',
      groupId: option.groupId
    }).then(res => {
      if (res.code === 200) {
        Message.success("编辑专家组成功");
        handleCancel();
        emits("list");
      }
    })
  }
}

const handleCancel = () => {
  option.visible = false
}

const show = () => {
  option.visible = true
  option.title = "添加专家组"
  option.groupId = ""
  option.type = "1"
  formData.groupName = ""
  formData.teacherIds = []
  formRef.value?.clearValidate()
  nextTick(() => {
    handleReset()
  })
}

const edit = (groupId: string, name: string, teacherIds: string[]) => {
  option.groupId = groupId
  option.visible = true
  option.title = "修改专家组"
  option.type = "2"
  formData.groupName = name
  formData.teacherIds = teacherIds
  formRef.value?.clearValidate()
  nextTick(() => {
    handleReset()
  })
}

defineExpose({
  show,
  edit
})

onMounted(() => {
  getDictByParentCode({
    dictCode: "参赛项目来源",
  }).then(res => {
    if (res.code === 200) {
      option["参赛项目来源"] = res.data[0].children
    }
  })
  listNormalRacetrack().then((res) => {
    if (res.code === 200) {
      listRacetrack().then((r) => {
        if (r.code === 200) {
          option["赛道"] = [
              ...r.data,
              ...res.data
          ]
        }
      });
    }
  });
})

const columns = [
  {
    title: '姓名',
    key: "trueName",
    dataIndex: "trueName",
    align: "center",
    width: 100,
  },
  {
    title: '电话',
    key: "phone",
    dataIndex: "phone",
    align: "center",
    width: 140,
  },
  {
    title: '来源',
    key: "city",
    dataIndex: "city",
    align: "center",
    width: 200,
  },
  {
    title: '领域',
    key: "channel",
    dataIndex: "channel",
    align: "center",
    width: 200,
  },
  {
    title: '单位',
    key: "unit",
    dataIndex: "unit",
    ellipsis: true,
    tooltip: true,
    align: "center",
    width: 140,
  },
  {
    title: '职务',
    key: "post",
    dataIndex: "post",
    ellipsis: true,
    tooltip: true,
    width: 140,
    align: "center"
  },
  {
    title: '职称',
    key: "title",
    dataIndex: "title",
    ellipsis: true,
    tooltip: true,
    width: 140,
    align: "center"
  },
  {
    title: '操作',
    slotName: "operate",
    align: "center",
    width: 100,
    // fixed: "right",
  },
]

const rules = {
  groupName: {
    required: true,
    message: "请输入专家组名称",
  },
  teacherIds: {
    required: true,
    message: "请选择专家",
  },
}

const handleRowClick = (record: {id: string}) => {
  if (formData.teacherIds.includes(record.id)) {
    formData.teacherIds = formData.teacherIds.filter((item: string) => item !== record.id)
  } else {
    formData.teacherIds.push(record.id)
  }
}
</script>

<template>
  <a-modal
      :visible="option.visible"
      :title="option.title"
      title-align="start"
      :mask-closable="false"
      :ok-loading="option.okLoading"
      ref="modalRef"
      :esc-to-close="false"
      width="80%"
      @cancel="handleCancel"
      @ok="handleOk"
      @beforeOk="handleSubmit"
  >
    <div style="height: 550px">
      <a-form layout="vertical" ref="formRef" :model="formData" :rules="rules">
        <a-form-item class="groupName" field="groupName" label="专家组名称">
          <a-input v-model="formData.groupName"></a-input>
        </a-form-item>
        <a-form-item label="专家列表" field="teacherIds">
          <div style="width: 100%">
            <div class="tabletools">
              <a-form layout="inline">
                <a-form-item label="来源">
                  <a-input  v-model="option.city" placeholder="请输入来源"></a-input>
                </a-form-item>
                <a-form-item label="领域">
                  <a-input  v-model="option.channel" placeholder="请输入领域"></a-input>
                </a-form-item>
                <a-form-item>
                  <a-space>
                    <a-button type="primary" @click="handleSearch">查询</a-button>
                    <a-button @click="handleReset">重置</a-button>
                  </a-space>
                </a-form-item>
              </a-form>
            </div>
            <a-table
                :columns="columns"
                :data="data"
                row-key="id"
                :pagination="pagination"
                @page-change="handlePageChange"
                :bordered="tableBorder"
                size="medium"
                :hoverable="true"
                :stripe="false"
                :row-selection="rowSelection"
                :selected-keys="formData.teacherIds"
                @select="handleSelect"
                @row-click="handleRowClick"
            >
              <template #operate="{ record }">
                <a-button type="outline" @click="handleDetail(record)">详情</a-button>
              </template>
            </a-table>
          </div>
        </a-form-item>
      </a-form>
    </div>
    <ExpertDetailModal ref="detailRef"/>
  </a-modal>
</template>

<style scoped lang="scss">
:deep(.arco-form-item){
  &.groupName {
    display: flex !important;
    gap: 24px;
    .arco-form-item-label-col {
      margin-top: 6px;
    }
    //align-items: center;
  }
}

</style>